#include "monitor.h"
#include <string>

using namespace std;

int monitor_writer::init_monitor(int ser,int size)
{
	int ret = 0;
	if(ser < 0) return -1;
	ret = init(ser, size);
	if(ret < 0) return ret;
	_content = (monitor_content *)get_memory();
	char *mem = (char *)get_memory();
	memset(mem, 0, monitor_writer::size());
	//memset(_content, 0, sizeof(*_content));

	//	pthread_mutex_init(&_mutex, NULL);
	return 0;
}

int monitor_writer::write_ip(char *ip){
	if(!has_init()){
		return -1;
	}
	memcpy(_content->_ip, ip, 15);
	_content->_ip[15] = '\0';
	return 0;
}

int monitor_writer::write_port(int port){
	if(!has_init()){
		return -1;
	}
	_content->_port = port;
	return 0;
}

int monitor_writer::write_start_time(long tv){
	if(!has_init()){
		return -1;
	}
	_content->_start_time = tv;
	return 0;
}

int monitor_writer::add_all_request_nums(){
	if(!has_init()){
		return -1;
	}
	_content->_all_request_nums ++;
	return 0;
}

int monitor_writer::add_valid_request_nums(){
	if(!has_init()){
		return -1;
	}
	_content->_valid_request_nums ++;
	return 0;
}

int monitor_writer::add_all_response_nums(){
	if(!has_init()){
		return -1;
	}
	__sync_add_and_fetch(&(_content->_all_response_nums), 1);
	return 0;
}


int monitor_writer::add_valid_response_nums(){
	if(!has_init()){
		return -1;
	}
	__sync_add_and_fetch(&(_content->_valid_response_nums), 1);
	return 0;
}

int monitor_writer::write_last_response_time(long tv){
	if(!has_init()){
		return -1;
	}
	_content->_last_response_time = tv;
}

int monitor_writer::write_last_handle_time(long long time){
	if(!has_init()){
		return -1;
	}
	_content->_last_handle_time = time;
}

int monitor_writer::write_max_delay(long long tv){
	if(!has_init()){
		return -1;
	}
//	pthread_mutex_lock(&_mutex);
    long long curDelay = _content->_max_delay;
	if(tv > curDelay){
        __sync_val_compare_and_swap(&(_content->_max_delay), curDelay, tv);
	}

	if(tv > 2000)
		__sync_add_and_fetch(&(_content->_delay_over_2s_nums), 1);
	else if(tv > 1000)
		__sync_add_and_fetch(&(_content->_delay_over_1s_nums), 1);
	else if(tv > 800)
		__sync_add_and_fetch(&(_content->_delay_over_800ms_nums), 1);
	else if(tv > 600)
		__sync_add_and_fetch(&(_content->_delay_over_800ms_nums), 1);
//	pthread_mutex_unlock(&_mutex);
}

int monitor_writer::add_all_delay(long long time){
	if(!has_init()){
		return -1;
	}
	__sync_add_and_fetch(&(_content->_all_delay), time);
}

int monitor_writer::write_wait_request_nums(int nums){
	if(!has_init()){
		return -1;
	}
	(_content->_wait_request_nums) = nums;
}


